import re
import json
import os
from datetime import datetime


def extract_knowledge_units(text):
    """
    从清洗后文本中提取细粒度知识单元，按类别结构化标注
    覆盖：设备参数、技术协议、网络优化、KPI指标、故障处理、工程部署、业务流程
    """
    knowledge_units = []
    unit_id_counter = {
        "device_param": 1,
        "technical_protocol": 1,
        "network_optimization": 1,
        "kpi_indicator": 1,
        "fault_handling": 1,
        "engineering_deployment": 1,
        "service_process": 1
    }

    # 1. 设备参数提取
    device_pattern = r'([华为|中兴|诺基亚|大唐].*?)(?:功耗|工作带宽|工作温度|输出功率|尺寸|容量规格|供电方式|通道数|工作频段|重量|传输接口|连接器类型|同步方式|最大功耗|平均功耗|输出功率).*?是([^，。；;]+)'
    device_matches = re.findall(device_pattern, text, re.S | re.IGNORECASE)
    for match in device_matches:
        device_info, param_value = match
        # 拆分品牌和型号
        if "华为" in device_info:
            brand = "华为"
            model = device_info.replace("华为", "").strip()
        elif "中兴" in device_info:
            brand = "中兴"
            model = device_info.replace("中兴", "").strip()
        elif "诺基亚" in device_info:
            brand = "诺基亚"
            model = device_info.replace("诺基亚", "").strip()
        elif "大唐" in device_info:
            brand = "大唐"
            model = device_info.replace("大唐", "").strip()
        else:
            brand = "其他"
            model = device_info.strip()

        # 提取参数类型
        param_type = ""
        if "功耗" in device_info:
            param_type = "功耗"
        elif "工作带宽" in device_info:
            param_type = "工作带宽"
        elif "工作温度" in device_info:
            param_type = "工作温度"
        elif "输出功率" in device_info:
            param_type = "输出功率"
        elif "尺寸" in device_info:
            param_type = "尺寸"
        elif "容量规格" in device_info:
            param_type = "容量规格"
        elif "供电方式" in device_info:
            param_type = "供电方式"
        elif "通道数" in device_info:
            param_type = "通道数"
        elif "工作频段" in device_info:
            param_type = "工作频段"
        elif "重量" in device_info:
            param_type = "重量"
        elif "传输接口" in device_info:
            param_type = "传输接口"
        elif "连接器类型" in device_info:
            param_type = "连接器类型"
        elif "同步方式" in device_info:
            param_type = "同步方式"

        # 补充参数单位
        if param_type == "功耗" and not any(unit in param_value for unit in ["W", "w", "dBm"]):
            param_value += "W"
        elif param_type == "工作温度" and not any(unit in param_value for unit in ["℃", "°C"]):
            param_value = param_value.replace("to", "～").replace("-", "～") + "℃"
        elif param_type == "尺寸" and "mm" not in param_value and "×" in param_value:
            param_value = param_value.replace("*", "×") + "mm"

        core_content = f"{brand}{model}的{param_type}为{param_value}"
        source_text = f"{device_info}{param_type}是{param_value}"
        unit = {
            "unit_id": f"device_param_{unit_id_counter['device_param']:03d}",
            "category": "device_param",
            "sub_category": "基站/射频设备参数",
            "core_content": core_content,
            "source_text": source_text,
            "device_brand": brand,
            "device_model": model,
            "param_type": param_type,
            "param_value": param_value,
            "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        knowledge_units.append(unit)
        unit_id_counter["device_param"] += 1

    # 2. 技术协议提取
    proto_pattern = r'([TD-LTE|NR|TD-SCDMA|GSM|WCDMA|CDMA2000|NB-IoT].*?)系统.*?(?:CP类型|传输模式|子载波间隔|TTI|PRB开销|同步信号|参考信号|帧结构|时隙配比|码片速率|调制方式).*?([^，。；;]+)'
    proto_matches = re.findall(proto_pattern, text, re.S | re.IGNORECASE)
    for match in proto_matches:
        tech_std, proto_detail = match
        tech_std = tech_std.strip()
        proto_detail = proto_detail.strip().replace("，", "；").replace("、", "；")

        # 提取核心内容
        if "CP类型" in proto_detail:
            core_content = f"{tech_std}系统的循环前缀（CP）类型为{proto_detail}"
        elif "传输模式" in proto_detail:
            core_content = f"{tech_std}系统中传输模式相关配置为{proto_detail}"
        elif "子载波间隔" in proto_detail:
            core_content = f"{tech_std}系统中子载波间隔配置为{proto_detail}"
        elif "TTI" in proto_detail:
            core_content = f"{tech_std}系统中传输时间间隔（TTI）为{proto_detail}"
        elif "PRB开销" in proto_detail:
            core_content = f"{tech_std}系统中PRB相关开销配置为{proto_detail}"
        elif "同步信号" in proto_detail:
            core_content = f"{tech_std}系统中同步信号（PSS/SSS/SSB）配置为{proto_detail}"
        elif "参考信号" in proto_detail:
            core_content = f"{tech_std}系统中参考信号（CRS/DM-RS/SRS）配置为{proto_detail}"
        elif "帧结构" in proto_detail:
            core_content = f"{tech_std}系统的帧结构参数为{proto_detail}"
        elif "时隙配比" in proto_detail:
            core_content = f"{tech_std}系统的时隙配比为{proto_detail}"
        elif "码片速率" in proto_detail:
            core_content = f"{tech_std}系统的码片速率为{proto_detail}"
        elif "调制方式" in proto_detail:
            core_content = f"{tech_std}系统支持的调制方式为{proto_detail}"
        else:
            core_content = f"{tech_std}系统的技术协议细节为{proto_detail}"

        source_text = f"{tech_std}系统{proto_detail}"
        unit = {
            "unit_id": f"technical_protocol_{unit_id_counter['technical_protocol']:03d}",
            "category": "technical_protocol",
            "sub_category": "空口协议/帧结构/信号配置",
            "core_content": core_content,
            "source_text": source_text,
            "tech_standard": tech_std,
            "protocol_detail": proto_detail,
            "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        knowledge_units.append(unit)
        unit_id_counter["technical_protocol"] += 1

    # 3. 网络优化参数提取 - 修复了正则表达式中的 '-' 转义问题
    opt_pattern = r'([threshServingLowPRSRP|A3Offset|CellIndividualOffset|s\-Measure|gapMCS|QsearchI].*?)是.*?(?:RSRP门限|切换门限|重选门限|优化措施|建议设置值).*?([-0-9~dBm;，。\s]+)'
    opt_matches = re.findall(opt_pattern, text, re.S | re.IGNORECASE)
    for match in opt_matches:
        param_name, param_detail = match
        param_name = param_name.strip()
        param_detail = param_detail.strip().replace("\n", "").replace("  ", " ")

        # 提取参数范围和建议值
        if "建议设置值" in param_detail:
            recommended_value = param_detail.split("建议设置值:")[-1].strip()
        elif "门限" in param_detail:
            recommended_value = param_detail.split("门限")[-1].strip()
        else:
            recommended_value = param_detail

        # 确定参数类型
        if "RSRP" in param_detail:
            param_type = "RSRP门限"
        elif "切换" in param_detail:
            param_type = "切换门限"
        elif "重选" in param_detail:
            param_type = "重选门限"
        elif "优化" in param_detail:
            param_type = "优化措施"
        else:
            param_type = "网络优化参数"

        core_content = f"{param_name}是{param_type}，建议设置值为{recommended_value}"
        source_text = f"{param_name}是{param_detail}"
        unit = {
            "unit_id": f"network_optimization_{unit_id_counter['network_optimization']:03d}",
            "category": "network_optimization",
            "sub_category": "切换/重选参数/优化措施",
            "core_content": core_content,
            "source_text": source_text,
            "param_scope": "4/5G IRAT切换/重选" if "IRAT" in source_text else "同频/异频优化",
            "param_type": param_type,
            "recommended_value": recommended_value,
            "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        knowledge_units.append(unit)
        unit_id_counter["network_optimization"] += 1

    # 4. KPI指标提取
    kpi_pattern = r'([无线掉话率|VoNR下行MOS值|同频硬切换成功率|无线接入成功率|覆盖率|PRB利用率].*?)计算公式为.*?([^，。；;]+)|([无线掉话率|VoNR下行MOS值|同频硬切换成功率].*?)=(.*?)×100%'
    kpi_matches = re.findall(kpi_pattern, text, re.S | re.IGNORECASE)
    for match in kpi_matches:
        if match[0] and match[1]:
            kpi_name, calc_logic = match[0].strip(), match[1].strip()
        else:
            kpi_name, calc_logic = match[2].strip(), match[3].strip()

        core_content = f"{kpi_name}的计算公式为：{kpi_name}={calc_logic}×100%" if "×100%" not in calc_logic else f"{kpi_name}的计算公式为：{kpi_name}={calc_logic}"
        source_text = f"{kpi_name}={calc_logic}×100%" if "×100%" not in calc_logic else f"{kpi_name}={calc_logic}"
        unit = {
            "unit_id": f"kpi_indicator_{unit_id_counter['kpi_indicator']:03d}",
            "category": "kpi_indicator",
            "sub_category": "关键性能指标",
            "core_content": core_content,
            "source_text": source_text,
            "kpi_name": kpi_name,
            "calculation_logic": calc_logic + "×100%" if "×100%" not in calc_logic else calc_logic,
            "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        knowledge_units.append(unit)
        unit_id_counter["kpi_indicator"] += 1

    # 5. 故障处理提取
    fault_pattern = r'([华为RRU风扇异常告警|GPS跑偏故障|直放站干扰|射频单元温度异常告警].*?)是指.*?([^，。；;]+)|([直放站|RRU|GPS].*?)可能产生的影响.*?([掉话率增高|通话质量差|误码率高|信噪比低].*?)'
    fault_matches = re.findall(fault_pattern, text, re.S | re.IGNORECASE)
    for match in fault_matches:
        if match[0] and match[1]:
            fault_type, fault_detail = match[0].strip(), match[1].strip()
            impact_content = ""
            handling_suggestion = ""
            if "风扇堵塞" in fault_detail:
                handling_suggestion = "清理风扇或更换风扇硬件"
            elif "GPS天线" in fault_detail:
                handling_suggestion = "检查GPS天线遮挡、功分器故障、时钟同步配置"
            elif "温度异常" in fault_detail:
                handling_suggestion = "检查散热通道或更换散热模块"
        else:
            fault_type = match[2].strip() + "影响"
            impact_content = match[3].strip()
            fault_detail = f"影响：{impact_content}"
            handling_suggestion = ""
            if "直放站" in fault_type:
                handling_suggestion = "调整直放站增益或优化施主小区选择"

        core_content = f"{fault_type}：{fault_detail}，处理建议：{handling_suggestion}" if handling_suggestion else f"{fault_type}：{fault_detail}，影响：{impact_content}"
        source_text = f"{fault_type}是指{fault_detail}" if match[0] else f"{fault_type}表现为{impact_content}"
        unit = {
            "unit_id": f"fault_handling_{unit_id_counter['fault_handling']:03d}",
            "category": "fault_handling",
            "sub_category": "设备告警/故障处理",
            "core_content": core_content,
            "source_text": source_text,
            "fault_type": fault_type,
            "impact_content": impact_content,
            "fault_cause": fault_detail.split("原因：")[-1] if "原因：" in fault_detail else "",
            "handling_suggestion": handling_suggestion,
            "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        knowledge_units.append(unit)
        unit_id_counter["fault_handling"] += 1

    return knowledge_units


def generate_json_lines(knowledge_units, output_path):
    """将知识单元列表生成JSON Lines格式文件"""
    with open(output_path, "w", encoding="utf-8") as f:
        for unit in knowledge_units:
            json.dump(unit, f, ensure_ascii=False, indent=None, separators=(",", ":"))
            f.write("\n")


# 主执行流程
if __name__ == "__main__":
    # 获取路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.dirname(script_dir)
    doc_path = os.path.join(project_root, "data", "cleaned_knowledge_base.txt")

    # 检查文件
    if not os.path.exists(doc_path):
        raise FileNotFoundError(f"文档文件不存在！请确认路径：{doc_path}")

    # 读取文本
    with open(doc_path, "r", encoding="utf-8") as f:
        cleaned_text = f.read()

    # 提取并生成结果
    units = extract_knowledge_units(cleaned_text)
    output_file = os.path.join(project_root, "data\knowledge_units.jsonl")
    generate_json_lines(units, output_file)

    print(f"知识单元拆分完成！")
    print(f"共生成 {len(units)} 个知识单元")
    print(f"输出文件路径：{output_file}")
